package com.et.machine.broadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.et.logger.ELog
import com.et.logger.TAGS
import com.et.machine.goods.*

private val pushMessageReceiver = PushMessageReceiver()
private const val ACTION_GOODS = "com.et.action.goods.change"
private const val ACTION_ADVERT = "com.et.action.advert.change"
private const val ACTION_DISCOUNT = "com.et.action.goods.discount"
private const val ACTION_PAY_TYPE = "com.et.action.pay.change"
private const val ACTION_GOODS_ADD = "com.et.action.goods.add.count"
private const val ACTION_GOODS_OUT = "com.et.action.goods.out"
private const val ACTION_MACHINE_CONFIG = "com.et.action.machine.config"
private const val ACTION_GATE_OPEN = "com.et.action.gate.open"

fun registerPushMessageReceiver(context: Context) {
    context.registerReceiver(pushMessageReceiver, IntentFilter().also {
        ELog.d(TAGS.machine, "machine:register push message receiver")
        it.addAction(ACTION_PAY_TYPE)
        it.addAction(ACTION_GOODS_ADD)
        it.addAction(ACTION_GOODS)
        it.addAction(ACTION_DISCOUNT)
        it.addAction(ACTION_ADVERT)
        it.addAction(ACTION_GOODS_OUT)
        it.addAction(ACTION_MACHINE_CONFIG)
        it.addAction(ACTION_GATE_OPEN)
    })
}

fun unRegisterPushMessageReceiver(context: Context) {
    context.unregisterReceiver(pushMessageReceiver)
}

class PushMessageReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context?, intent: Intent?) {
        ELog.d(TAGS.machine, "machine:broadcast Receiver:${intent?.getStringExtra("json")}")
        intent?.let {
            when (it.action) {
                ACTION_GOODS -> {
                    it.getStringExtra("json")?.let { json ->
                        goodsUpdate(json)
                    }
                }
                ACTION_GOODS_ADD -> {
                    it.getStringExtra("json")?.let { json ->
                        goodsCountUpdate(json)
                    }
                }
                ACTION_GOODS_OUT -> {
                    it.getStringExtra("json")?.let { json ->
                        outGoods(json)
                    }
                }
                ACTION_MACHINE_CONFIG -> {
                    it.getStringExtra("json")?.let { json ->
                        tempLightUpdate(json)
                    }
                }
                ACTION_DISCOUNT -> {
                    it.getStringExtra("json")?.let { json ->
                        discountUpdate(json)
                    }
                }

                else -> {

                }
            }
        }
    }

}